package com.leonzhangxf.server.service;

import com.leonzhangxf.common.JSONSerializer;
import com.leonzhangxf.common.RpcRequest;
import com.leonzhangxf.common.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    private ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    private Serializer serializer = new JSONSerializer();

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        RpcRequest rpcRequest = serializer.deserialize(RpcRequest.class, bytes);
        if (null == rpcRequest) {
            return;
        }

        Class<?> aClass = Class.forName(rpcRequest.getClassName());
        try {
            Method method = aClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
            Object bean = applicationContext.getBean(aClass);
            Object result = method.invoke(bean, rpcRequest.getParameters());
            ctx.writeAndFlush(result);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
